package cn.wolfcode.trip.admin.filter;

import cn.wolfcode.trip.base.util.SevenUploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 这个filter只会拦截,/upload开头的请求,在保存时同一保存/upload目录下面
 */
public class ImageFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //过滤图片的资源,
        HttpServletRequest req = (HttpServletRequest)request;
        //从请求中获得请求图片的url路径,此时的url就是图片资源的名字
        String imageUrl = req.getRequestURI();
        //判断上面的imageUrl是否在共享空间中,如果存在,就拦截,将共享空间中的图片资源返回
        File file = new File(SevenUploadUtil.domainName+imageUrl);
        if (file.exists()){
            //将图片下载返回
            byte[] bytes = FileUtils.readFileToByteArray(file);
            response.getOutputStream().write(bytes);
        }else {
            //放行
            chain.doFilter(req,response);
        }
    }
    public void destroy() {

    }
}
